package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 根据状态查询需要认证相关的用户信息
     *
     * @param dto
     * @return
     */
    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    ArticleFeign articleFeign;


    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        // 1 参数检查

        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 2 条件查询


        IPage<ApUserRealname> pageParam = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<ApUserRealname> query = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            query.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> pageResult = page(pageParam, query);
        // 3 返回结果
        return new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal()
                , pageResult.getRecords());
    }

    /**
     * 根据状态进行审核
     *
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1 参数检查

        if (dto == null || dto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2 查询当前认证用户是否在 APP端有当前用户
        ApUserRealname userRealname = getById(dto.getId());
        if (userRealname == null || userRealname.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //获取apUser的id
        ApUser apUser = apUserMapper.selectById(userRealname.getId());
        if (apUser == null || apUser.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3 修改状态
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        //拒绝原因
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);

        //4 认证状态如果为 通过
        if (status.intValue() == AdminConstants.PASS_AUTH.intValue()) {
            //5 更新APP用户状态
            WmUser wmUser = createWmuser(dto, apUser);

            if (wmUser == null || wmUser.getId() == null) {
                CustException.cust(AppHttpCodeEnum.WMUSER_ADD_EXIST);
            }

            //远程创建作者账号
            boolean flag = createApAuthor(wmUser);
            if (!flag) {
                CustException.cust(AppHttpCodeEnum.AUTHOR_ADD_EXIST);
            }
            //更新APUser数据中的flag为1
            apUser.setFlag((short) 1);
            apUserMapper.updateById(apUser);
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 4.2 创建作者信息
     *
     * @param wmUser
     * @return
     */
    private boolean createApAuthor(WmUser wmUser) {
//1 查询当前作者是否存在，不存在则新增
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setCreatedTime(new Date());
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(AdminConstants.AUTHOR_TYPE); // 自媒体人类型
            apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
            apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
            ResponseResult result = articleFeign.save(apAuthor);
            // 判断成功执行
            if (result.getCode() == 0) {
                return true;
            }
        }

        return false;

    }

    /**
     * 创建自媒体账号
     *
     * @param dto
     * @param apUser
     * @return
     */
    private WmUser createWmuser(AuthDto dto, ApUser apUser) {
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setImage(apUser.getImage());
            wmUser.setName(apUser.getName());
            wmUser.setNickname(apUser.getName());
            wmUser.setSalt(apUser.getSalt());  // 盐
            wmUser.setPassword(apUser.getPassword()); // 密码
            wmUser.setPhone(apUser.getPhone());
            wmUser.setCreatedTime(new Date());
            wmUser.setType(0); // 个人
            wmUser.setScore(100);
            wmUser.setStatus(0);
            return wemediaFeign.save(wmUser);
        }
        return null;
    }
}
